

const fs = require('fs');
const { resolve, extname } = require('path');

/**
 * 
 * @param {string} url 路径
 */
const dirToJson = (url) => {
    //1. 判断是文件还是目录
    if (fs.statSync(url).isFile()) { //是文件
        return {
            name: url,
            path: resolve(url),
            type: extname(url).slice(1)
        }
    } else { //是目录
        return {
            name: url,
            path: resolve(url),
            type: '文件夹',
            children: fs.readdirSync(url).map((item) => { //递归调用
                return dirToJson(url + '/' + item);
            })
        }
    }
}

let res = dirToJson('public');
fs.writeFileSync('data.json', JSON.stringify(res));